<template>
  <el-dialog
    :close-on-click-modal="false"
    modal-append-to-body
    lock-scroll
    top="10%"
    :title="$t('config.agent.modifyAgent')"
    :visible.sync="dialogVisible"
    @close="close"
    width="50%"
  >
    <p class="note">{{ $t('config.agent.editAgentTip') }}</p>
    <el-form :model="form" :rules="rules" ref="form" label-position="top" label-width="80px">
      <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('public.name')" prop="displayName">
            <el-input
              v-model.trim="form.displayName"
              :placeholder="$t('agentSetting.agentSetting57')"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2"> &nbsp;</el-col>
        <el-col :span="11">
          <el-form-item :label="$t('public.jobNumber')" prop="exten">
            <el-input
              v-model.trim="form.exten"
              :disabled="isEditExten"
              :placeholder="$t('config.agent.pleaseExten')"
              size="mini"
              @blur="changeJobNum"
            ></el-input>
          </el-form-item>
          <div v-if="isShowTip" class="tip-color">{{ $t('agentSetting.agentSetting58') }}</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('agentSetting.agentSetting1')">
            <el-input
              v-model.trim="extenType"
              disabled
              :placeholder="$t('config.agent.editAgentTip')"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2"> &nbsp;</el-col>
        <el-col :span="11">
          <el-form-item :label="$t('agentSetting.agentSetting2')">
            <el-input v-model.trim="inheritAgent" disabled placeholder="" size="mini"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.phoneNumber')" prop="mobile">
            <el-input
              v-model.trim="form.mobile"
              :disabled="isInherit"
              :placeholder="$t('config.agent.pleasePhone')"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2"> &nbsp;</el-col>
        <el-col :span="11">
          <el-form-item :label="$t('public.email')">
            <el-input
              v-model.trim="form.ivrInfo.email"
              :placeholder="$t('config.agent.pleaseEmail')"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('public.nickName')">
            <el-input
              v-model.trim="form.nickName"
              auto-complete="off"
              :placeholder="$t('agentSetting.agentSetting3')"
              size="mini"
            ></el-input>
            <span class="tip">
              <el-tooltip transition="fade-leave" effect="dark" :content="$t('public.nickNameTip')" placement="bottom">
                <i class="icon iconfont icon-tixingweizhi"></i>
              </el-tooltip>
            </span>
          </el-form-item>
        </el-col>
        <el-col :span="2"> &nbsp;</el-col>
        <el-col :span="11">
          <el-form-item :label="$t('public.password')">
            <el-input
              readonly
              onfocus="this.removeAttribute('readonly')"
              autocomplete="new-password"
              v-model.trim="form.ivrInfo.password"
              :placeholder="$t('config.agent.pleasePassword')"
              type="password"
              size="mini"
            ></el-input>
            <div class="recommended-pwd">{{ $t('agentSetting.agentSetting4') }}:{{ recommendedPwd }}</div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.dept')" prop="deptId">
            <dept
              ref="ownerSelect"
              :style="'width:100%'"
              :placeholder="$t('config.agent.pleaseDept')"
              :addDepts="depts"
              :dept="form.deptId"
              @deptChange="deptChange"
            ></dept>
          </el-form-item>
        </el-col>
        <el-col :span="2"> &nbsp;</el-col>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.parentAgent')">
            <!-- <agent-select
                :placeholder = "$t('config.agent.pleaseParentAgent')"
                @agentChange = "agentChange"
                :customfield = "customize"
                :agent = "form.parentId"
                ref = "agnetSelect">
              </agent-select> -->
            <m7Select
              class="el-select"
              :placeholder="$t('config.agent.pleaseParentAgent')"
              filterable
              :options="selectAgents"
              v-model="form.parentId"
            ></m7Select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('agentSetting.agentSetting5')">
            <el-select v-model="form.uversion" size="mini" :disabled="isUversion">
              <el-option v-for="item in Package" :label="item.label" :key="item.value" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 角色组件 -->
      <!-- <el-form-item :label="$t('config.agent.modifyRole')" prop="role">
          <role-transfer
            :rolesId = "rolesId"
            ref = "child">
          </role-transfer>
        </el-form-item> -->
      <el-form-item :label="$t('config.agent.modifyRole')" prop="role">
        <role-transfer-new :rolesId="rolesId" ref="roleChild"> </role-transfer-new>
      </el-form-item>
      <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('configTabTitle.callQueueConfig')">
            <el-select v-model.trim="form.callQueues" size="mini" multiple filterable collapse-tags>
              <el-option v-for="item in callQueueList" :key="item._id" :label="item.DisplayName" :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2"> &nbsp;</el-col>
        <el-col :span="11">
          <el-form-item :label="$t('configTabTitle.webchatQueueConfig')">
            <el-select v-model.trim="form.mailQueues" size="mini" multiple filterable collapse-tags>
              <el-option v-for="item in webchatQueueList" :key="item._id" :label="item.DisplayName" :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.minImDealCount')">
            <el-input v-model.trim="form.minImDealCount" size="mini"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2"> &nbsp;</el-col>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.maxImDealCount')">
            <el-input v-model.trim="form.maxImDealCount" size="mini"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.maxEmailDealCount')">
            <el-input
              v-model.trim="form.maxEmailDealCount"
              :placeholder="$t('config.agent.defaultTen')"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2"> &nbsp;</el-col>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.AutoBusyTime')" class="ipt_append">
            <el-input placeholder=" " v-model.trim="form.ivrInfo.AutoBusyTime" size="mini" :disabled="isInherit">
              <template slot="append">{{ $t('public.seconds') }}</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.minimumAgentsCount')">
            <el-input v-model.trim="form.minimumAgentsCount" size="mini"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2"> &nbsp;</el-col>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.maximumAgentsCount')">
            <el-input v-model.trim="form.maximumAgentsCount" size="mini"></el-input>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.imAgentStatusInit')" prop="imClaimStatus">
            <el-radio-group v-model="form.imClaimStatus">
              <el-radio :label="'open'">{{ $t('config.agent.onlineStatus') }}</el-radio>
              <el-radio :label="'close'">{{ $t('config.agent.busyStatus') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="2"> &nbsp;</el-col>
        <el-col :span="11">
          <el-form-item :label="$t('config.agent.automaticStatusInit')" prop="autoOrderInitStatus">
            <el-radio-group v-model="form.autoOrderInitStatus">
              <el-radio :label="'order'">{{ $t('config.agent.orderStatus') }}</el-radio>
              <el-radio :label="'busy'">{{ $t('config.agent.busyStatus') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-form-item :label="$t('config.agent.emailClaimStatus')" prop="emailClaimStatus">
        <el-radio-group v-model="form.emailClaimStatus">
          <el-radio :label="'open'">{{ $t('config.agent.open') }}</el-radio>
          <el-radio :label="'close'">{{ $t('config.agent.close') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('config.agent.callautobusy')">
        <el-radio-group v-model="form.CallInAutoBusy">
          <el-radio :label="true">{{ $t('config.agent.open') }}</el-radio>
          <el-radio :label="false">{{ $t('config.agent.close') }}</el-radio>
        </el-radio-group>
        <p v-show="form.CallInAutoBusy">
          {{ $t('config.agent.callInAutoBusyCount1')
          }}<el-input
            v-model="form.CallInAutoBusyCount"
            @input="CallInAutoBusyCountInput"
            type="number"
            style="width: 70px"
          ></el-input
          >{{ $t('config.agent.callInAutoBusyCount2') }}
        </p>
      </el-form-item>
      <el-form-item :label="$t('config.agent.iscallinternation')">
        <el-radio-group v-model="form.iscallinternation">
          <el-radio :label="true">{{ $t('config.agent.open') }}</el-radio>
          <el-radio :label="false">{{ $t('config.agent.close') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('config.agent.allowLandingMode')">
        <el-checkbox v-model="form.localLoginWay">{{ $t('config.agent.localLoginWay') }}</el-checkbox>
        <el-checkbox v-model="form.gatewayLoginWay">{{ $t('config.agent.gatewayLoginWay') }}</el-checkbox>
        <el-checkbox v-model="form.sipLoginWay">{{ $t('config.agent.onLineServer') }}</el-checkbox>
        <el-checkbox v-model="form.appLoginWay">{{ $t('config.agent.appLoginWay') }}</el-checkbox>
        <el-checkbox v-model="form.weChatAssistantLoginWay">{{ $t('agentSetting.agentSetting6') }}</el-checkbox>
        <span class="bind_font" v-if="!isBindWebchat">({{ $t('agentSetting.agentSetting7') }})</span>
        <span v-if="isBindWebchat"
          >({{ $t('agentSetting.agentSetting9') }},
          <span class="unbind" @click="unbindWebchat(form._id)">{{ $t('agentSetting.agentSetting8') }}</span
          >)</span
        >
      </el-form-item>
      <el-form-item :label="$t('config.agent.isSoftphoneDial')">
        <el-radio-group v-model="form.closeSoftphoneDial">
          <el-radio :label="false">{{ $t('config.agent.open') }}</el-radio>
          <el-radio :label="true">{{ $t('config.agent.close') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('config.agent.isWebSoftTelephone')">
        <el-radio-group v-model="form.webSoftTelephone">
          <el-radio :label="true">{{ $t('config.agent.open') }}</el-radio>
          <el-radio :label="false">{{ $t('config.agent.close') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('config.agent.isMoniterAgent')">
        <el-radio-group v-model="form.ivrInfo.type">
          <el-radio :label="'manager'" :disabled="isInherit">{{ $t('public.yes') }}</el-radio>
          <el-radio :label="'agent'" :disabled="isInherit">{{ $t('public.no') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('config.agent.callTodoWebchatSwitch')">
        <el-radio-group v-model="form.callIngWebchatSwitch">
          <el-radio :label="'yes'">{{ $t('public.yes') }}</el-radio>
          <el-radio :label="'no'">{{ $t('public.no') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('agentSetting.agentSetting59')">
        <el-radio-group v-model="form.businessSmsNotice">
          <el-radio :label="true">{{ $t('config.agent.open') }}</el-radio>
          <el-radio :label="false">{{ $t('config.agent.close') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item class="search">
        <el-button @click="close" class="primary_btn">{{ $t('public.cancel') }}</el-button>
        <el-button type="primary" @click="onSubmit(form)" class="primary_btn">{{ $t('public.save') }}</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import Dept from '@/components/public-modules/cache/Dept'
import { checkform } from '@/utils/validate'
import AgentSelect from '@/components/public-modules/cache/AgentSelect'
// import RoleTransfer from '@/components/public-modules/cache/RoleTransfer'
import RoleTransferNew from '@/components/public-modules/cache/RoleTransferNew'
import { deepClone, isHasMenu } from '@/utils/m7Utils.js'
export default {
  name: 'EditAgent',
  data() {
    let validate1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('validate.required')))
      } else if (checkform(value, 'Number')) {
        callback(new Error(this.$t('customer.shouldBeNumber')))
      } else {
        callback()
      }
    }
    let validate2 = (rule, value, callback) => {
      if (!value && this.form.businessSmsNotice) {
        callback(new Error(this.$t('agentSetting.agentSetting60')))
      } else if (checkform(value, 'Number')) {
        callback(new Error(this.$t('customer.shouldBeNumber')))
      } else {
        callback()
      }
    }
    return {
      isEditExten: false,
      oldExten: '',
      isShowTip: false,
      isBindWebchat: false, // 是否绑定客服助手
      isInherit: false, // 是否为附属工号
      extenType: this.$t('agentSetting.agentSetting61'),
      inheritAgent: '', // 继承座席工号
      recommendedPwd: '', // 推荐密码
      dialogVisible: false, // 当前弹窗绑定值
      rolesId: [], // 初始化角色子组件右侧角色
      maxNumber: [], // 渲染座席最大能同时接待会话下拉
      minNumber: [], // 渲染座席最小能同时接待会话下拉
      callQueueList: [], // 电话技能组
      webchatQueueList: [], // 在线技能组
      customize: [],
      depts: [
        {
          // 添加请选择项
          label: this.$t('public.pleasePick1'),
          value: ''
        }
      ],
      Package: [], // 座席使用版本渲染数据
      isIvrInfo: false, // 判断是否传IvrInfo
      cloneIvrInfo: {}, // 和之前IvrInfo对比用
      form: {
        inheritedFrom: '', // 附属工号id
        nickName: '', // 昵称
        _id: '', // 当前座席id
        deptId: '', // 部门id
        parentId: '', // 座席上级id
        role: [], // 角色id数组
        imClaimStatus: 'open', // 在线咨询自动领取开关
        // autoOrderInitStatus: 'order',
        emailClaimStatus: 'close', // 邮件自动领取开关
        maxImDealCount: '', // 最大能同时接待会话
        minImDealCount: '', // 最小能同时接待会话
        // maximumAgentsCount: '', // 座席最小接单数量上限
        // minimumAgentsCount: '', // // 座席最小接单数量上限
        iscallinternation: true, // 是否开启国际电话服务
        CallInAutoBusy: false, //是否开启呼入自动置忙
        CallInAutoBusyCount: 3, //呼入自动置忙次数
        maxEmailDealCount: '', // 座席最大能同时处理邮件数
        gatewayLoginWay: true, // sip话机
        localLoginWay: true, // 手机
        appLoginWay: true, // app
        sipLoginWay: true, // 在线客服
        weChatAssistantLoginWay: true, // 微信客服助手
        displayName: '', // 姓名
        uversion: '', // 座席使用版本
        exten: '', // 工号
        mobile: '', // 电话
        ivrInfo: {
          _id: '',
          displayName: '',
          exten: '',
          mobile: '',
          email: '',
          AutoBusyTime: '', // 后处理时长
          uversion: '',
          type: '', // 是否为监控座席
          password: ''
        },
        businessSmsNotice: false, // 是否开启工单短信通知
        callIngWebchatSwitch: 'yes', // 来电时是否接入在线咨询
        closeSoftphoneDial: false, // 企话宝拨号盘是否启用
        webSoftTelephone: false, // web电话自动接听是否启用
        callQueues: [],
        mailQueues: []
      },
      rules: {
        // 饿了么校验规则
        displayName: [{ required: true, message: this.$t('config.agent.pleaseName'), trigger: 'blur' }],
        exten: [{ required: true, validator: validate1, trigger: 'blur' }],
        mobile: [{ validator: validate2, trigger: 'blur' }],
        // uversion: [
        //   { required: true, message: this.$t('config.agent.pleasePackageType'), trigger: 'change' }
        // ],
        role: [{ required: true, message: this.$t('config.agent.pleaseRole'), type: 'array' }]
      },
      agentOptions: [] // 座席数据
    }
  },
  props: {
    isEdit: Boolean, // 弹窗开关
    agentDetail: Object // 座席信息
  },
  computed: {
    // 判断是否为过滤座席 返回座席下拉数据
    selectAgents() {
      let define = [{ label: this.$t('config.agent.pleaseParentAgent'), value: '' }]
      if (this.$store.getters.userHidden === 'yes') {
        let agentList =
          this.$store.getters.filterStopAgents &&
          this.$store.getters.filterStopAgents.map((agent) => ({
            label: `${agent.displayName}[${agent.exten}]`,
            value: agent._id
          }))
        console.log('agentList', agentList)
        return [...define, ...agentList]
      }
      return [...define, ...this.agentOptions]
    },
    isUversion() {
      // 判断是不是计费跳转 是则可修改版本
      if (this.$store.state.session.user.type !== 'admin' && this.$store.state.session.user.exten !== '0000') {
        return true
      } else {
        return false
      }
    }
  },
  watch: {
    isEdit(cur, old) {
      this.dialogVisible = this.isEdit
      cur && this.init()
    }
  },
  components: {
    Dept,
    AgentSelect,
    // RoleTransfer,
    RoleTransferNew
  },
  methods: {
    changeJobNum() {
      let that = this
      if (that.form.exten !== that.oldExten) {
        that.isShowTip = true
      } else {
        that.isShowTip = false
      }
    },
    unbindWebchat(id) {
      let text = this.$t('agentSetting.agentSetting66')
      this.$confirm(text, this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        type: 'warning',
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn'
      }).then(() => {
        this.$emit('unbindWebchat', id)
        this.dialogVisible = false
      })
    },
    randomWord(min, max) {
      let str = ''
      let range = min
      let arr = [
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
        'i',
        'j',
        'k',
        'l',
        'm',
        'n',
        'o',
        'p',
        'q',
        'r',
        's',
        't',
        'u',
        'v',
        'w',
        'x',
        'y',
        'z',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ]
      // 随机产生
      range = Math.round(Math.random() * (max - min)) + min
      for (let i = 0; i < range; i++) {
        let pos = Math.round(Math.random() * (arr.length - 1))
        str += arr[pos]
      }
      return str
    },
    updatePwd() {
      let _pattern = '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$'
      let _pwd = this.randomWord(8, 11)
      while (!_pwd.match(_pattern)) {
        _pwd = this.randomWord(8, 11)
      }
      let teStr = '#_!'
      let _numRan = Math.floor(Math.random() * 4)
      let _arrayStr = _pwd.split('')
      _arrayStr.splice(_numRan, 0, teStr.charAt(_numRan))
      this.recommendedPwd = _arrayStr.join('')
      let data = {
        Account: this.$store.state.session.account.account,
        pbx: this.form.pbx
      }
      this.$store.dispatch('queryQueueForSkill', data).then((res) => {
        if (res.success) {
          this.callQueueList = res.list || []
        }
      })
      this.$store.dispatch('getDicCache', { type: 'mailQueues' }).then((res) => {
        if (res && res.success) {
          this.webchatQueueList = res.data || []
        } else {
          this.webchatQueueList = []
        }
      })
    },
    // 渲染套餐类型字段
    showPackage() {
      let Packages = this.$getCache('licenceType')
      Packages.map((item) => {
        this.Package.push({
          label: item.code_name,
          value: item.code_value
        })
      })
    },
    onSubmit(form) {
      // 声明正整数校验规则
      let isPositiveNum = /^[0-9]*[1-9][0-9]*$/
      let greatZero = /^\+?\d*$/
      let numberTest = /^[1-9]\d*$/
      if (!numberTest.test(this.form.minImDealCount) || !numberTest.test(this.form.maxImDealCount)) {
        this.$message.error(this.$t('config.agent.imDealErroTip2'))
        return
      }
      // else if (!numberTest.test(this.form.minimumAgentsCount) || !numberTest.test(this.form.maximumAgentsCount)) {
      //   this.$message.error(this.$t('config.agent.mumAgentsCountErroTip2'))
      //   return
      // } else if (parseInt(this.form.minimumAgentsCount) > parseInt(this.form.maximumAgentsCount)) {
      //   this.$message.error(this.$t('config.agent.mumAgentsCountErroTip'))
      //   return
      // }
      else if (parseInt(this.form.minImDealCount) > parseInt(this.form.maxImDealCount)) {
        this.$message.error(this.$t('config.agent.imDealErroTip'))
        return
      } else if (parseInt(this.form.minImDealCount) > 200 || parseInt(this.form.maxImDealCount) > 200) {
        this.$message.error(this.$t('config.agent.imDealErroTip2'))
        return
      }
      // else if (parseInt(this.form.minimumAgentsCount) > 200 || parseInt(this.form.maximumAgentsCount) > 200) {
      //   this.$message.error(this.$t('config.agent.mumAgentsCountErroTip2'))
      //   return
      // }
      else if (this.form.maxEmailDealCount && !isPositiveNum.test(this.form.maxEmailDealCount)) {
        this.$message.error(this.$t('config.agent.EmailDealErroTip'))
        return
      } else if (this.form.ivrInfo.AutoBusyTime && !greatZero.test(this.form.ivrInfo.AutoBusyTime)) {
        this.$message.error(this.$t('config.agent.AutoBusyTimeErro'))
        return
      }
      if (!this.form.ivrInfo.AutoBusyTime) {
        // 后处理为空时添加默认值
        this.form.ivrInfo.AutoBusyTime = '0'
        this.cloneIvrInfo.AutoBusyTime = '0' // 给clone的也赋值，避免后面提交表单的时候，判断不相等，没修改也给后端传了ivrInfo
      }
      // 判断角色是否为空
      // if (this.getRoleIds(this.$refs.child.selected).length !== 0) {
      //   form.role = this.getRoleIds(this.$refs.child.selected)
      // } else {
      //   form.role = []
      // }
      if (this.$refs.roleChild.selected !== 0) {
        form.role = this.$refs.roleChild.selected
      } else {
        form.role = []
      }
      // 表单校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 成功执行
          let data = deepClone(form)
          // 判断工号
          if (data.exten.length !== 4 && data.exten.length !== 5) {
            this.$message.error(this.$t('agentSetting.agentSetting63'))
            return
          } else if (
            data.exten.length === 4 &&
            (data.exten.substring(0, 1) === '0' || data.exten.substring(0, 1) === '9')
          ) {
            this.$message.error(this.$t('agentSetting.agentSetting64'))
            return
          } else if (
            data.exten.length === 5 &&
            (data.exten.substring(0, 1) === '0' ||
              data.exten.substring(0, 1) === '9' ||
              data.exten.substring(0, 1) === '1')
          ) {
            this.$message.error(this.$t('agentSetting.agentSetting65'))
            return
          }
          // if (data.exten && (data.exten.length !== 4 || data.exten.substring(0, 1) === '0' || data.exten.substring(0, 1) === '9')) {
          //   this.$message.error(this.$t('config.agent.extenErroMessage'))
          //   return
          // }
          // 密码校验
          let passwordNew = data.ivrInfo.password
          if (passwordNew !== null && passwordNew !== '') {
            let regexPass = false
            let lengthRegex = new RegExp('^.{8,}$') // >= 8位
            let characterRegex = new RegExp('[a-z]') // 小寫
            let characterRegex2 = new RegExp('[A-Z]') // 大寫
            let numberRegex = new RegExp('[0-9]') // 數字
            let chinese = new RegExp('[\\u4E00-\\u9FFF]+', 'g') // 是否有中文
            let num = 0
            let temporary = data.ivrInfo.password
            temporary = temporary.replace(/[^0-9a-zA-Z]/g, '')
            if (characterRegex.test(passwordNew)) {
              num += 1
            }
            if (characterRegex2.test(passwordNew)) {
              num += 1
            }
            if (numberRegex.test(passwordNew)) {
              num += 1
            }
            if (passwordNew.length - temporary.length > 0) {
              num += 1
            }
            if (num >= 3) {
              regexPass = true
            } else {
              regexPass = false
            }
            if (!lengthRegex.test(passwordNew)) {
              regexPass = false
            }
            if (chinese.test(passwordNew)) {
              regexPass = false
            }
            let limitArr = ['%', '&', '"', "'", '<', '>', '+', '=']
            for (let i = 0; i < limitArr.length; i++) {
              if (passwordNew.indexOf(limitArr[i]) > -1) {
                regexPass = false
                break
              }
            }
            if (!regexPass) {
              this.$message.error(this.$t('config.agent.newPasswordRule'))
              return
            }
          }
          // 给data.ivrInfo的校验字段赋值
          data.ivrInfo.displayName = data.displayName
          data.ivrInfo.mobile = data.mobile
          data.ivrInfo.exten = data.exten
          data.ivrInfo.uversion = data.uversion
          data.ivrInfo.CallInAutoBusy = data.CallInAutoBusy
          data.ivrInfo.CallInAutoBusyCount = data.CallInAutoBusyCount
          delete data.uversion
          delete data.displayName
          delete data.mobile
          delete data.exten
          delete data.CallInAutoBusyCount
          delete data.CallInAutoBusy
          // 判断是否需改了displayName, mobile, exten, uversion 这几个字段，如果修改了就传
          for (let key in this.cloneIvrInfo) {
            if (this.cloneIvrInfo[key] !== data.ivrInfo[key]) {
              this.isIvrInfo = true
            }
          }
          // 如果密码为空不传密码项
          data.ivrInfo.password === '' && delete data.ivrInfo.password
          if (!this.isIvrInfo) {
            delete data.ivrInfo
          } else {
            if (this.isUversion) {
              data.ivrInfo.uversion && delete data.ivrInfo.uversion
            }
          }
          this.isIvrInfo = false
          console.log(data)
          console.log('edit-----agent')
          this.$emit('EditAgent', data)
          this.dialogVisible = false
        }
      })
    },
    getRoleIds(arr) {
      let ids = []
      arr.map((item) => {
        ids.push(item.value)
      })
      return ids
    },
    deptChange(deptId) {
      this.form.deptId = deptId
    },
    agentChange(parentId) {
      this.form.parentId = parentId
    },
    // 循环座席能同时接待会话数
    forNumber(num, obj) {
      for (let i = 1; i < num + 1; i++) {
        obj.push({
          label: i + '',
          value: i + ''
        })
      }
    },
    // 避免后端没有返回字段
    dealType(basicType) {
      return basicType === undefined ? true : basicType
    },
    // 出始化修改详情
    init() {
      this.isShowTip = false
      this.rolesId = this.agentDetail.role
      this.form.role = this.agentDetail.role
      this.form.nickName = this.agentDetail.nickName || ''
      this.form._id = this.agentDetail._id
      this.form.imClaimStatus = this.agentDetail.imClaimStatus === undefined ? 'open' : this.agentDetail.imClaimStatus
      // this.form.autoOrderInitStatus = this.agentDetail.autoOrderInitStatus === undefined ? 'order' : this.agentDetail.autoOrderInitStatus
      this.form.emailClaimStatus =
        this.agentDetail.emailClaimStatus === undefined ? 'close' : this.agentDetail.emailClaimStatus
      this.form.maxImDealCount = this.agentDetail.maxImDealCount
      this.form.minImDealCount = this.agentDetail.minImDealCount
      // this.form.minimumAgentsCount = this.agentDetail.minimumAgentsCount || 1
      // this.form.maximumAgentsCount = this.agentDetail.maximumAgentsCount || 10
      this.form.deptId = this.agentDetail.deptId
      this.form.parentId = this.agentDetail.parentId
      this.form.iscallinternation = this.dealType(this.agentDetail.iscallinternation)
      this.form.CallInAutoBusy = !!this.agentDetail.CallInAutoBusy
      this.form.CallInAutoBusyCount = this.agentDetail.CallInAutoBusyCount || 3
      this.form.maxEmailDealCount = this.agentDetail.maxEmailDealCount
      this.form.gatewayLoginWay = this.dealType(this.agentDetail.gatewayLoginWay)
      this.form.appLoginWay = this.dealType(this.agentDetail.appLoginWay)
      this.form.sipLoginWay = this.dealType(this.agentDetail.sipLoginWay)
      this.form.localLoginWay = this.dealType(this.agentDetail.localLoginWay)
      this.form.weChatAssistantLoginWay = this.dealType(this.agentDetail.weChatAssistantLoginWay)
      this.form.displayName = this.agentDetail.displayName
      this.oldExten = deepClone(this.agentDetail.exten)
      this.form.exten = this.agentDetail.exten
      this.form.mobile = this.agentDetail.mobile
      this.form.uversion = this.agentDetail.uversion
      this.form.ivrInfo.password = ''
      this.form.ivrInfo._id = this.agentDetail._id
      this.form.ivrInfo.email = this.agentDetail.email
      this.form.ivrInfo.type = this.agentDetail.type
      this.form.ivrInfo.AutoBusyTime = this.agentDetail.AutoBusyTime
      this.form.ivrInfo.displayName = this.agentDetail.displayName
      this.form.ivrInfo.mobile = this.agentDetail.mobile
      this.form.ivrInfo.exten = this.agentDetail.exten
      this.form.ivrInfo.uversion = this.agentDetail.uversion
      this.form.inheritedFrom = this.agentDetail.inheritedFrom
      this.form.callQueues = this.agentDetail.callQueues
      this.form.mailQueues = this.agentDetail.mailQueues
      this.form.ivrInfo.CallInAutoBusy = !!this.agentDetail.CallInAutoBusy
      this.form.ivrInfo.CallInAutoBusyCount = this.agentDetail.CallInAutoBusyCount || 3
      this.cloneIvrInfo = deepClone(this.form.ivrInfo)
      this.form.callIngWebchatSwitch = this.agentDetail.callIngWebchatSwitch || 'yes'
      this.form.closeSoftphoneDial = !!this.agentDetail.closeSoftphoneDial
      this.form.businessSmsNotice = this.agentDetail.businessSmsNotice || false
      this.form.webSoftTelephone = this.agentDetail.webSoftTelephone || false
      if (this.agentDetail.weChatHelperBindStatus === 'unbind') {
        this.isBindWebchat = false
      } else {
        this.isBindWebchat = true
      }
      if (this.agentDetail.inheritedFrom) {
        this.extenType = this.$t('agentSetting.agentSetting62')
        this.inheritAgent = this.$agentsMap()[this.agentDetail.inheritedFrom].exten
        this.isInherit = true
      } else {
        this.extenType = this.$t('agentSetting.agentSetting61')
        this.inheritAgent = ''
        this.isInherit = false
      }
      // console.log(this.form)
    },
    close() {
      this.$emit('close')
    },
    CallInAutoBusyCountInput(value) {
      if (value <= 1) {
        this.form.CallInAutoBusyCount = 1
      } else if (value >= 99) {
        this.form.CallInAutoBusyCount = 99
      }
    }
  },
  beforeMount() {
    this.$store.dispatch('getCache', { type: 'agents' }).then((agents) => {
      agents.map((agent) => {
        this.agentOptions.push({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id })
      })
    })
    this.forNumber(200, this.maxNumber)
    this.forNumber(50, this.minNumber)
    this.showPackage()
    if (
      isHasMenu('func_not_allow_edit_agent_exten', this.$store.state.session.user) ||
      this.$store.state.session.user.isAdmin
    ) {
      this.isEditExten = true
    }
  },
  mounted() {}
}
</script>
<style lang="stylus" scoped>
@import "../../../../../../assets/common.styl"
.tip-color
  color $c-pink
  font-size 12px
  bottom: -10px
  line-height normal
  position absolute
.el-select
  width 100%
.unbind
  color $c-email
  cursor pointer
.bind_font
  font-size 12px
.note
  color $c-prompt
.el-input
  font-size 12px
.el-form-item
  margin-top 10px
.search
  text-align center
.recommended-pwd
  font-size 12px
.tip
  position absolute
  top 10px
  cursor pointer
  display inline-block
  height 16px
  width 16px
  border 1px solid $c-main
  text-align center
  line-height 15px
  border-radius 50%
  margin 0px 0 0 6px
  .iconfont
    border none
    font-size 10px
    color $c-main
</style>
